﻿using FastCode.Architecture;
using FastCode.DTO;
using FastCode.Helper;
using FastCode.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace FastCode.Controllers
{
    //[Authorize]
    public class UserController : ApiControllerBase<User>
    {
        readonly UserService userService;
        //private readonly UserManager<IdentityUser> _userManager;
        private readonly IConfiguration _configuration;


        public UserController(ISqlSugarClient _db, UserService _userService, IConfiguration configuration) : base(_db)
        {
            userService = _userService;
            //_userManager = userManager;
            _configuration = configuration;
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Msg> Register(UserDTO model)
        {
            if (await db.Queryable<User>().AnyAsync(x => x.UserName == model.UserName))
            {
                return Msg.Error("用户已存在");
            }

            var user = new User
            {
                UserName = model.UserName,
            };
            user.LastLoginDate = DateTime.Now;
            user.Salt = PasswordHasherF.GenerateSalt();
            user.PasswordHash = PasswordHasherF.ComputeHash(model.Password, user.Salt);
            var token = GetToken(user);
            await db.Insertable(user).ExecuteCommandAsync();

            return Msg.Success(token);
        }
        [HttpPost]
        public async Task<Msg> ChangePwd(ChangePwdDTO model)
        {
            var user = await userService.GetCurrentUserAsync();

            var computedPwd = PasswordHasherF.ComputeHash(model.OldPassword, user.Salt??string.Empty);
            //当前登录
            if (user.PasswordHash != computedPwd)
            {
                return Msg.Error("密码错误");
            }

            user.PasswordHash = PasswordHasherF.ComputeHash(model.NewPassword, user.Salt);
            user.PasswordLastUpdated = DateTime.Now;

            await db.Updateable(user).ExecuteCommandAsync();

            return Msg.Success("修改成功");
        }


        private string GetToken(User user)
        {
            return PasswordHasherF.GenerateJwtToken(user, _configuration.GetValue<string>("Jwt:Secret") ?? string.Empty, _configuration.GetValue<string>("Jwt:Issuer") ?? string.Empty, _configuration.GetValue<string>("Jwt:Audience") ?? string.Empty, 120);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Msg> Login(UserDTO model)
        {

            var user = await db.Queryable<User>().FirstAsync(x => x.UserName == model.UserName);
            if (user == null)
            {
                return Msg.Error("用户不存在");
            }
            var computedPwd = PasswordHasherF.ComputeHash(model.Password, user.Salt);
            //当前登录
            if (user.PasswordHash != computedPwd)
            {
                return Msg.Error("密码错误");
            }
            var token = GetToken(user);

            return Msg.Success(new { token, userId = user.Id, userName = user.UserName }, message: "登录成功");
        }
    }
}
